using MallApi.Middlewares;
using Microsoft.EntityFrameworkCore;
using Models.Models;
using Scalar.AspNetCore;
using Services;
using MallApi.Common;
using MallApi.Filters;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers(options =>
{
    options.Filters.Add<ModelValidationFilter>();
}).AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null; // 保持属性名称不变
});

builder.Services.Configure<Microsoft.AspNetCore.Mvc.ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true; // 关闭自动400响应
});


// 配置数据库连接
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ShopxoContext>(options =>
    options.UseMySql(connectionString, ServerVersion.Parse("5.7.43-mysql")));

builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// 注册服务
builder.Services.AddScoped<IHomeService, HomeService>();
builder.Services.AddScoped<IUserService, UserService>();

builder.Services.AddOpenApi();

// 配置跨域
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll",
        builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
        });
});

var app = builder.Build();

app.UseGlobalExceptionMiddleware();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}

// 启用跨域
app.UseCors("AllowAll");

// 使用JWT中间件
app.UseMiddleware<JwtMiddleware>();

app.UseAuthorization();

app.MapControllers();

app.Run();